<?php
/*
 * @Author: 李志刚
 * @CopyRight: 2020-2030 衡水山木枝技术服务有限公司
 * @Date: 2021-09-11 15:24:40
 * @Description: 拼多多订单处理
 * @LastEditors: 李志刚
 * @LastEditTime: 2021-09-30 16:04:46
 * @FilePath: /qingshanERP/app/Http/Controllers/Tenant/OrderPddController.php
 */

namespace App\Http\Controllers\Tenant;

use DB;
use Log;
use Validator;
use Illuminate\Http\Request;
use App\Customize\PddRequest;
use App\Models\QingShanERP\Shop;
use App\Models\QingShanERP\Order;
use App\Models\Tenant\ShopToShop;
use App\Http\Controllers\Controller;
use App\Models\QingShanERP\GoodSpec;
use App\Models\QingShanERP\OrderLog;
use App\Models\QingShanERP\Supplier;
use App\Models\QingShanERP\Logistics;
use App\Models\QingShanERP\OrderGood;
use App\Models\QingShanERP\GoodSupplier;
use App\Models\QingShanERP\OrderPddData;
use App\Models\QingShanERP\SupplierStaff;
use App\Models\QingShanERP\GoodSpecSupplier;
use App\Models\QingShanERP\OrderPddTracking;
use App\Models\Tenant\SupplierContactTenant;

class OrderPddController extends Controller
{
    public function getList(Request $request)
    {
        try {
            $page = $request->input('page', 0);
            $size = $request->input('size', 10);
            $supplier_id = $request->input('supplier_id', '');
            $confirm_status = $request->input('confirm_status', '');
            $order_status = $request->input('order_status', '');
            $after_sales_status = $request->input('after_sales_status', '');
            $supplier_order_status = $request->input('supplier_order_status', '');
            $remark_tag = $request->input('remark_tag', '');
            $key = $request->input('key', '');
            $tracking_number = $request->input('tracking_number', '');
            if ($request->tenant->super) {
                $shopid = Shop::where('tenant_id',$request->tenant->tid)->where('del_flag',0)->pluck('id');
            }else {
                $shopid = ShopToShop::where('shop_id', $request->tenant->id)->pluck('shop2_id');
            }
            $list = Order::with(['shop' => function ($q) {
                $q->select('id', 'shopname');
            }, 'supplier', 'pdd', 'goods', 'supplier_staff'])->where(function ($q) use ($shopid) {
                    $q->whereIn('shop_id', $shopid);
            })->where(function ($q) use ($supplier_id) {
                if ($supplier_id != '') {
                    $q->where('supplier_id', $supplier_id);
                }
            })->where(function ($q) use ($remark_tag) {
                if ($remark_tag != '') {
                    $q->where('remark_tag', '!=', $remark_tag);
                }
            })->where(function ($q) use ($confirm_status) {
                if ($confirm_status != '') {
                    $q->where('confirm_status', $confirm_status);
                }
            })->where(function ($q) use ($order_status) {
                if ($order_status != '') {
                    $q->where('order_status', $order_status);
                }
            })->where(function ($q) use ($after_sales_status) {
                if ($after_sales_status == '0') {
                    $q->where('after_sales_status', 0);
                } elseif ($after_sales_status > 0) {
                    $q->where('after_sales_status', '>', 0);
                }
            })->where(function ($q) use ($supplier_order_status) {
                if ($supplier_order_status != '') {
                    $q->where('supplier_order_status', $supplier_order_status);
                }
            })->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('order_sn', 'like', '%' . $key . '%');
                }
            })->where(function ($q) use ($tracking_number) {
                if ($tracking_number != '') {
                    $q->where('tracking_number', $tracking_number);
                }
            })->where('del_flag', 0)->offset(($page - 1) * $size)->limit($size)->orderBy('confirm_time', 'desc')->get();
            $count = Order::where(function ($q) use ($shopid) {
                    $q->whereIn('shop_id', $shopid);
            })->where(function ($q) use ($supplier_id) {
                if ($supplier_id != '') {
                    $q->where('supplier_id', $supplier_id);
                }
            })->where(function ($q) use ($remark_tag) {
                if ($remark_tag != '') {
                    $q->where('remark_tag', '!=', $remark_tag);
                }
            })->where(function ($q) use ($confirm_status) {
                if ($confirm_status != '') {
                    $q->where('confirm_status', $confirm_status);
                }
            })->where(function ($q) use ($order_status) {
                if ($order_status != '') {
                    $q->where('order_status', $order_status);
                }
            })->where(function ($q) use ($after_sales_status) {
                if ($after_sales_status == '0') {
                    $q->where('after_sales_status', 0);
                } elseif ($after_sales_status > 0) {
                    $q->where('after_sales_status', '>', 0);
                }
            })->where(function ($q) use ($supplier_order_status) {
                if ($supplier_order_status != '') {
                    $q->where('supplier_order_status', $supplier_order_status);
                }
            })->where(function ($q) use ($key) {
                if ($key != '') {
                    $q->where('order_sn', 'like', '%' . $key . '%');
                }
            })->where(function ($q) use ($tracking_number) {
                if ($tracking_number != '') {
                    $q->where('tracking_number', $tracking_number);
                }
            })->where('del_flag', 0)->count();
            $res = ['list' => $list, 'total' => $count];
            return $this->resData(200, '获取数据成功...', $res);
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 分配供应商
    public function postSupplier(Request $request)
    {
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->input(), [
                'supplier_id' => 'required|integer',
                'order_ids' => 'required|array',
            ]);
            $attrs = array(
                'supplier_id' => '供应商',
                'order_ids' => '订单'
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                DB::rollback();
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $supplier_id = $request->input('supplier_id');
            $tenant_id = $request->tenant->tid;
            $supplier = Supplier::where('status', 1)->where('del_flag', 0)->findOrFail($supplier_id);
            if (is_null($supplier)) {
                DB::rollback();
                return $this->resData(400, '供应商不存在');
            }
            $order_ids = $request->input('order_ids', []);
            if (!count($order_ids)) {
                DB::rollback();
                return $this->resData(400, '请选择要操作的订单');
            }
            // 看下是不是都没有分配，有分配过的不允许重新分配
            $order_status = Order::where('tenant_id', $tenant_id)->whereIn('id', $order_ids)->where('order_status', '!=', 1)->count();
            if ($order_status) {
                DB::rollback();
                return $this->resData(400, '存在已发货订单，请重新选择');
            }
            $hav = Order::where('tenant_id', $tenant_id)->whereIn('id', $order_ids)->where('supplier_id', '!=', 0)->count();
            if ($hav) {
                DB::rollback();
                return $this->resData(400, '请选择未分配供应商的订单');
            }
            // 开始更新
            Order::where('tenant_id', $tenant_id)->whereIn('id', $order_ids)->update(['supplier_id' => $supplier_id]);
            $all_order = Order::with('goods')->whereIn('id', $order_ids)->get();
            $all_supplier_spec = GoodSpecSupplier::where('del_flag', 0)->where('supplier_id', $supplier_id)->get();
            $all_supplier = GoodSupplier::where('del_flag', 0)->where('supplier_id', $supplier_id)->get();
            // 记录日志
            foreach ($all_order as $o) {
                OrderLog::create(['order_id' => $o->id, 'user_type' => 1, 'user_id' => $request->tenant->id, 'log_name' => '分配供应商', 'url' => 'c-api/order/pddsupplier', 'data' => $supplier_id]);
                // 订单商品对应信息更新
                $supplier_price = 0;
                $shipping = 0;
                foreach ($o->goods as $g) {
                    $supplier_spec = $all_supplier_spec->where('good_spec_id', $g->good_spec_id)->first();
                    $supplier_name = $all_supplier->where('good_id', $g->good_id)->first();
                    if (is_null($supplier_spec)) {
                        DB::rollback();
                        return $this->resData(400, $g->good_spec_name . ' : 没有对应的供应商规格...');
                    }
                    OrderGood::where('id', $g->id)->update(['good_supplier_name' => is_null($supplier_name) ? '无' : $supplier_name->good_name, 'good_supplier_spec_name' => $supplier_spec->spec, 'supplier_price' => $supplier_spec->price, 'shipping' => $supplier_spec->shipping]);
                    $supplier_price = $supplier_price + $g->goods_count * $supplier_spec->price;
                    $shipping = $shipping + $g->goods_count * $supplier_spec->shipping;
                }
                Order::where('id', $o->id)->update(['supplier_price' => $supplier_price, 'shipping' => $shipping]);
            }
            DB::commit();
            return $this->resData(200, '分配成功...');
        } catch (\Throwable $th) {
            DB::rollback();
            return $this->resData(500, '添加失败，请重新操作...', $th->getMessage());
        }
    }
    // 发货、重发 pdd.logistics.online.send , 要记录下日志，重发需要限制在24小时内，改一下，支持批量发货
    public function postTrack(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'supplier_staff_id' => 'required|integer',
                'order_id' => 'required|integer',
                'order_track_id' => 'required|integer',
            ]);
            $attrs = array(
                'supplier_staff_id' => '员工',
                'order_id' => '订单号',
                'order_track_id' => '面单ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $tenant_id = $request->tenant->tid;
            // 查单号
            // $all['order_id'] = '12585';
            $logistics = OrderPddTracking::where('id', $all['order_track_id'])->first();
            if (is_null($logistics) || $logistics->status == 0 || $logistics->order_id != $all['order_id'] || $logistics->del_flag == 1) {
                return $this->resData(400, '此面单号不可用...');
            }
            $order = Order::with('supplier')->where('tenant_id', $tenant_id)->where('id', $all['order_id'])->first();
            if (is_null($order)) {
                return $this->resData(400, '没有此订单...');
            }
            if ($order->supplier_order_status == 1 && strtotime($order->shipping_time) < time() - 3600 * 24) {
                return $this->resData(400, '订单发货已经超过24小时，不能修改订单号...');
            }
            // 拼多多接口发货
            $params['access_token'] = PddRequest::getToken($order->shop_id);
            if (is_null($params['access_token'])) {
                return $this->resData(400, '此门店授权已过期，请先重新授权...');
            }
            $params['logistics_id'] = $logistics->logistics_id;
            $params['order_sn'] = $order->order_sn;
            $params['tracking_number'] = $logistics->tracking_number;
            // 供应商的退货地址
            // $params['refund_address_id'] = $order->supplier->refund_address_id;
            $result = PddRequest::request('pdd.logistics.online.send', $params);
            // 请求成功
            if (isset($result['logistics_online_send_response']) && $result['logistics_online_send_response']['is_success']) {
                // 更新订单信息，供货商发货
                Order::where('id', $all['order_id'])->update(['supplier_staff_id' => $all['supplier_staff_id'], 'supplier_order_status' => 1, 'logistics_id' => $logistics->logistics_id, 'tracking_number' => $logistics->tracking_number, 'shipping_time' => date('Y-m-d H:i:s')]);
                OrderPddTracking::where('id', $logistics->id)->update(['status' => 0]);
                // 如果是换单号，删掉以前那个
                if (!is_null($order->tracking_number)) {
                    OrderPddTracking::where('tracking_number', $order->tracking_number)->update(['del_flag' => 1]);
                }
                return $this->resData(200, '发货成功...');
            } else {
                return $this->resData(400, '拼多多发货失败，请稍后重发...', $result);
            }
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 批量发货
    public function postTrackM(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'order_id' => 'required|array',
            ]);
            $attrs = array(
                'order_id' => '订单号',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $supplier_staff_id = $request->supplier->id;
            $supplier_id = SupplierStaff::where('id', $supplier_staff_id)->value('supplier_id');
            // 查单号
            // $all['order_id'] = '12585';
            foreach ($request->input('order_id', []) as $order_id) {
                $order = Order::with('supplier')->where('id', $order_id)->first();
                if (is_null($order)) {
                    return $this->resData(400, '没有此订单...');
                }
                $logistics = OrderPddTracking::where('order_id', $order_id)->where('del_flag', 0)->where('status', 1)->first();
                if (is_null($logistics)) {
                    return $this->resData(400, $order->order_sn . ' 无面单号可用...');
                }
                if ($order->supplier_order_status == 1 && strtotime($order->shipping_time) < time() - 3600 * 24) {
                    return $this->resData(400, '订单发货已经超过24小时，不能修改订单号...');
                }
                // 拼多多接口发货
                $params['access_token'] = PddRequest::getToken($order->shop_id);
                if (is_null($params['access_token'])) {
                    return $this->resData(400, '此门店授权已过期，请先重新授权...');
                }
                $params['logistics_id'] = $logistics->logistics_id;
                $params['order_sn'] = $order->order_sn;
                $params['tracking_number'] = $logistics->tracking_number;
                $result = PddRequest::request('pdd.logistics.online.send', $params);
                // 请求成功
                if (isset($result['logistics_online_send_response']) && $result['logistics_online_send_response']['is_success']) {
                    // 更新订单信息，供货商发货
                    Order::where('id', $order_id)->update(['supplier_staff_id' => 0, 'supplier_order_status' => 1, 'logistics_id' => $logistics->logistics_id, 'tracking_number' => $logistics->tracking_number, 'shipping_time' => date('Y-m-d H:i:s')]);
                    OrderPddTracking::where('id', $logistics->id)->update(['status' => 0]);
                    // 如果是换单号，删掉以前那个
                    if (!is_null($order->tracking_number)) {
                        OrderPddTracking::where('tracking_number', $order->tracking_number)->update(['del_flag' => 1]);
                    }
                } else {
                    return $this->resData(400, '拼多多发货失败，请稍后重发...', $result);
                }
            }
            return $this->resData(200, '发货成功...');
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 补发 pdd.order.upload.extra.logistics , 要记录下日志
    public function reissueTrack(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'supplier_staff_id' => 'required|integer',
                'order_id' => 'required|integer',
                'order_track_id' => 'required|integer',
            ]);
            $attrs = array(
                'supplier_staff_id' => '员工',
                'order_id' => '订单号',
                'order_track_id' => '面单ID',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $tenant_id = $request->tenant->tid;
            // 查单号
            $logistics = OrderPddTracking::where('id', $all['order_track_id'])->first();
            if (is_null($logistics) || $logistics->status == 0 || $logistics->order_id != $all['order_id'] || $logistics->del_flag == 1) {
                return $this->resData(400, '此面单号不可用...');
            }
            $order = Order::where('tenant_id', $tenant_id)->where('id', $all['order_id'])->first();
            if (is_null($order)) {
                return $this->resData(400, '没有此订单...');
            }
            // 拼多多接口发货
            $params['access_token'] = PddRequest::getToken($order->shop_id);
            if (is_null($params['access_token'])) {
                return $this->resData(400, '此门店授权已过期，请先重新授权...');
            }
            // 开始接口发
            $params['order_sn'] = $order->order_sn;
            $params['extra_track_list'] = ['shipping_id' => $logistics->logistics_id, 'tracking_number' => $logistics->tracking_number];
            $result = PddRequest::request('pdd.order.upload.extra.logistics', $params);
            // 请求成功
            if (isset($result['upload_extra_logistics_response']) && $result['upload_extra_logistics_response']['success']) {
                // 更新补发信息进附表
                // $insert = [];
                // foreach ($all['logistics'] as $v) {
                //     $insert[] = ['order_id' => $all['order_id'], 'supplier_staff_id' => $all['supplier_staff_id'], 'logistics_id' => $v['logistics_id'], 'tracking_number' => $v['tracking_number'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
                // }
                // OrderPddTracking::insert($insert);
                OrderPddTracking::where('id', $logistics->id)->update(['status' => 0]);
                return $this->resData(200, '补发货成功...');
            } else {
                return $this->resData(400, '拼多多补发货失败，请稍后重发...', $result);
            }
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 补发 pdd.order.upload.extra.logistics , 要记录下日志
    public function reissueTrackNumber(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'supplier_staff_id' => 'required|integer',
                'order_id' => 'required|integer',
                'logistics' => 'required|array',
            ]);
            $attrs = array(
                'supplier_staff_id' => '员工',
                'order_id' => '订单号',
                'logistics' => '运单信息',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            // 查单号
            // $all['order_id'] = '12585';
            $tenant_id = $request->tenant->tid;
            $order = Order::where('tenant_id', $tenant_id)->where('id', $all['order_id'])->first();
            if (is_null($order)) {
                return $this->resData(400, '没有此订单...');
            }
            // 拼多多接口发货
            $params['access_token'] = PddRequest::getToken($order->shop_id);
            if (is_null($params['access_token'])) {
                return $this->resData(400, '此门店授权已过期，请先重新授权...');
            }
            // 开始接口发
            $params['order_sn'] = $order->order_sn;
            $params['extra_track_list'] = $all['logistics'];
            $result = PddRequest::request('pdd.order.upload.extra.logistics', $params);
            // 请求成功
            if (isset($result['upload_extra_logistics_response']) && $result['upload_extra_logistics_response']['success']) {
                // 更新补发信息进附表
                $insert = [];
                foreach ($all['logistics'] as $v) {
                    $wp_code = Logistics::where('logistics_id', $v['logistics_id'])->where('type', 4)->where('del_flag', 0)->where('status', 1)->value('logistics_code');
                    $insert[] = ['order_id' => $all['order_id'], 'supplier_staff_id' => $all['supplier_staff_id'], 'logistics_id' => $v['logistics_id'], 'wp_code' => $wp_code, 'tracking_number' => $v['tracking_number'], 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s')];
                }
                OrderPddTracking::insert($insert);
                return $this->resData(200, '补发货成功...');
            } else {
                return $this->resData(400, '拼多多补发货失败，请稍后重发...', $result);
            }
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 获取电子面单加密信息 pdd.waybill.get
    public function postWaybill(Request $request)
    {
        DB::beginTransaction();
        try {
            $validator = Validator::make($request->input(), [
                'order_id' => 'required|array',
                'wp_code' => 'required',
            ]);
            $attrs = array(
                'order_id' => '订单号',
                'wp_code' => '物流公司',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                DB::rollback();
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            $tenant_id = $request->tenant->tid;
            $waybill = [];
            // 查单号
            foreach ($request->input('order_id',[]) as $order_id) {
                // dd($tenant_id.' - '. $order_id);
                // $all['order_id'] = '12585';
                $order = Order::with(['shop', 'supplier', 'pdd', 'goods'])->where('tenant_id', $tenant_id)->where('id', $order_id)->first();
                if (is_null($order)) {
                    DB::rollback();
                    return $this->resData(400, '没有此订单...');
                }
                $userid = str_replace('pdd', '', $order->shop->shopid);
                $all_numbers = OrderPddTracking::where('order_id', $order_id)->where('del_flag', 0)->get();
                if ($all_numbers->count() > 0) {
                    $modules = [];
                    foreach ($all_numbers as $a) {
                        $modules[] = json_decode($a->waybill, true);
                    }
                    $waybill[] = ['userid' => $userid, 'waybill' => $modules];
                }
                // 请求面单号
                $params['access_token'] = PddRequest::getToken($order->shop_id);
                if (is_null($params['access_token'])) {
                    DB::rollback();
                    return $this->resData(400, '此门店授权已过期，请先重新授权...');
                }
                // 物流公司Code
                $wp_code = $all['wp_code'];
                // 找这家店的物流表信息
                $logistics = Logistics::where('shop_id', $order->shop_id)->where('logistics_code', $wp_code)->where('status', 1)->where('del_flag', 0)->first();
                // 发货人信息，应该在供应商下加入此信息，通过订单来找这个信息
                $sender = [
                    'name' => $order->shop->shopname,
                    'mobile' => $order->shop->phone,
                    'address' => [
                        'province' => $logistics->province,
                        'city' => $logistics->city,
                        'district' => $logistics->district,
                        'detail' => $logistics->detail,
                    ]
                ];
                // 请求面单信息，数量限制为10
                $items = [];
                foreach ($order->goods as $g) {
                    $items[] = ['count' => $g->goods_count, 'name' => $g->good_supplier_spec_name];
                }
                $total_count = $order->goods->sum('goods_num');
                $trade_order_info_dtos = [
                    [
                        'object_id' => time(),
                        'template_url' => $logistics->standard_template_url,
                        'user_id' => $userid,
                        'order_info' => [
                            // 订单平台、单号
                            'order_channels_type' => 'PDD',
                            'trade_order_list' => [$order->order_sn],
                        ],
                        'package_info' => [
                            // 子母件总包裹数 $order->goods->sum('goods_num')
                            'total_packages_count' => $total_count,
                            // 对应供应商产品名与规格名
                            'items'    =>   $items
                        ],
                        'recipient' => [
                            'name' => $order->pdd->receiver_name,
                            'mobile' => $order->pdd->receiver_phone,
                            'address' => [
                                'province' => $order->pdd->province,
                                'city' => $order->pdd->city,
                                'district' => $order->pdd->town,
                                'town' => $order->pdd->town,
                                'detail' => $order->pdd->receiver_address,
                            ]
                        ],
                    ]
                ];
                $params['param_waybill_cloud_print_apply_new_request'] = ['sender' => $sender, 'wp_code' => $wp_code, 'trade_order_info_dtos' => $trade_order_info_dtos];
                // $waybill[] = ['userid' => $userid, 'waybill' => ['{"print_data":"{\"encryptedData\":\"a67d4819d0cd21554e9437e0bc2caa629864b0effd1aec65833023f78e93733ca9eec3468dc487b24682b9d64f176ca641b43da305b5a9783d4618113f90da7c7235422173194fc934ed473db026fa554318612c670fd65c10808c688c00b2ee801ad70fbef67accd59725fbd0e230e6a5424d6497dfc3afed1302fe5e06f7517fb091f21ea0ff542beffc65e5891615270a899c48b25cdf88fd4512f2339103013f8fb7472129e0311db08046c5e0100ada55d00e5773a179f095c0b1962bb649e33d0fa768b2a66264cef007a2f33450822c871ed103048e6c1308dcc66a00285e77d33efc2c19e0d96ade51883dc8c269a946ffe147fd43f49c34c09daaee8ac65c4fa37c9f67f8841152e2d0f0c161af434562126f216259ca45d9a64842328758556196f75312199e85b6409403514325644e057485cac1d55f4481483fbee614ba701a34288f43628063785e35c6d07ddfc8011fd4b5c328e0718ef43ee33ff3811f6349654c45c9d002149dc17b4c1c6228fecc71c6e625eda5c03b858843fdf3ac856f2ef8e1676c2d2b5ba56ee188e1c014db98147cfa0ee88c4359ce8d5ab2b60b700de0786208adb8c72220a5783841685b3edacf04404cf702234715477529b5618e6ac4444fd388a1a81445f93cb2617cd849291dfb0417170d0dbca206a7e66a5c7f675d97b621d061a7acb345e9fd71b1fa438ce5847b1959f008aa035ee55260800954099422fe94fe434e0cb9a6ea0f6c7da9f2a41b9e92925bda8577b72f8a5293b54c2c9d70f33de462bd7ca8874300e2f98d74197f9095d208dc35006c223ae849814d33ff39c60ecba365dbcf37ca78f3b9a1143e8495a49802b6da02611203eeb56a61a6352422b0a1fdd9c038c0ec42071e865cedc584cdaec71b4a65b1ecb9f9c077bf252a110aed650b1dc4efd15a3ec01f3e61dc19d529d18109423f3c0b49e0614402ec33ebd80de9eaecf86557262d97dc819e6a352abcb319016825bcdd5ab6abbc41cd920a4769a690fafcfb407d6a8169587ca3cb6b08e79c53fc16b7e0aa936925fff53b238d28344de4b2d60d8bb04f49dbe1b313ca197e4497e5cbe5c9123a0b0bd2e2218544b757e03b2909ead53e7b8d5ffffe1ac0e8edd0baed5dba0630a971a255073ac0d34e50df80abcb1164a5a48ffd5bf61798f6d334eeac298eb1cb13c15f5b79d1b93d63b9dfa7a007df63df11d8858d2cce4e0af9447ad36888b769082ce52180c20dce746e3645df9fd6a9ea6f61b90e48101f81600ba4f62d0599a5e4d67d250e7cddfdb62fec4be2fb35f11a0dbd2ad31457c74327e62ed00f39a75ea289d64462e6bacb628355bb5dfcd9ace09fc443b9f6d2b00814b9a419b32725a7629c1983bd87646a1078bb6f4273098a369cf0c379aaed5a7e3cff2a4872b6ff756e98ba366715b11bd183f27c228008c0c74e22030bb5bd7fdba9\",\"signature\":\"MN\/BRYhm7wRRyVtm4\/fOn+ZGVlVhURpUwxYmyxwF7A0YnOvdBbF8IMBXyDMfMzvqpEL9AKYt56X6U8s1LeOwGK3r+H3G+k2w3Epk\/byyb0cD7IxpSTuwEBXDAEJz32F9WL7+KBQMWxJAftytOXQyzlg9MAS1jfg3umGw6IR8Ilw=\",\"templateUrl\":\"https:\/\/file-link.pinduoduo.com\/db_one\",\"ver\":\"3\"}","waybill_code":"DPK368059034588","object_id":"1625451653"}']];
                // dd($params);
                $result = PddRequest::request('pdd.waybill.get', $params);
                // dd($result);
                if (isset($result['pdd_waybill_get_response'])) {
                    // 记录面单信息，重新打印用
                    $insert = [];
                    $date = date('Y-m-d H:i:s');
                    $logistics_id = Logistics::where('logistics_code', $wp_code)->where('type', 4)->where('status', 1)->where('del_flag', 0)->value('logistics_id');
                    foreach ($result['pdd_waybill_get_response']['modules'] as $v) {
                        $insert[] = ['order_id' => $order_id, 'supplier_staff_id' => 0, 'logistics_id' => $logistics_id, 'wp_code' => $wp_code, 'tracking_number' => $v['waybill_code'], 'waybill' => json_encode($v), 'created_at' => $date, 'updated_at' => $date];
                    }
                    OrderPddTracking::insert($insert);
                    $waybill[] = ['userid' => $userid, 'waybill' => $result['pdd_waybill_get_response']['modules']];
                } else {
                    DB::rollback();
                    return $this->resData(400, '拼多多获取面单失败，请稍后再试...',$result);
                }
            }
            DB::commit();
            return $this->resData(200, '获取成功', $waybill);
        } catch (\Throwable $th) {
            DB::rollback();
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 拿所有面单号
    public function postOrderTrack(Request $request)
    {
        try {
            $validator = Validator::make($request->input(), [
                'order_id' => 'required|integer',
            ]);
            $attrs = array(
                'order_id' => '订单号',
            );
            $validator->setAttributeNames($attrs);
            if ($validator->fails()) {
                // 如果有错误，提示第一条
                return $this->resData(400, $validator->errors()->all()[0] . '...');
            }
            $all = $request->all();
            // 查单号
            $logistics = OrderPddTracking::where('order_id', $all['order_id'])->where('del_flag', 0)->get();
            return $this->resData(200, '发货成功...', $logistics);
        } catch (\Throwable $th) {
            return $this->resData(500, '获取数据失败，请稍后再试...', $th->getMessage());
        }
    }
    // 按时间段同步订单
    public function postSyncTime(Request $request){
        $start_time = $request->input('starttime',strtotime('2021-09-30 00:00:00'));
        $end_time = $request->input('endtime', strtotime('2021-10-01 00:00:00'));
        $j = ceil(($end_time - $start_time)/86400000) + 1;
        // 找所有门店
        $all_shop = Shop::where('type', 4)->where('tenant_id',$request->tenant->tid)->where('del_flag', 0)->where('id', 1)->get();
        foreach ($all_shop as $s) {
            // 如果token有效
            if ($s->expires_at >= time() && !is_null($s->access_token)) {
                for ($i = 0; $i < $j; $i++) {
                    $data = [];
                    $params['access_token'] = $s->access_token;
                    $params['timestamp'] = strval(time());
                    $params['order_status'] = 5;
                    $params['start_confirm_at'] = $start_time + $i * 24 * 60 * 60;
                    $params['end_confirm_at'] = $start_time + ($i + 1) * 24 * 60 * 60;
                    $params['page_size'] = 100;
                    $params['refund_status'] = 5;
                    $params['use_has_next'] = true;
                    $params['page'] = 1;
                    // 循环拉取一天的订单
                    $has_next = true;
                    while ($has_next) {
                        $tmp = PddRequest::request('pdd.order.list.get', $params);
                        if (!isset($tmp['order_list_get_response'])) {
                            Log::info('按时间同步订单，拉取失败：'.$tmp['error_response']['error_msg']);
                        } else {
                            $has_next = $tmp['order_list_get_response']['has_next'];
                            if ($has_next) {
                                $params['page'] = $params['page'] + 1;
                            }
                            if (is_array($tmp['order_list_get_response']['order_list'])) {
                                $data = array_merge($data, $tmp['order_list_get_response']['order_list']);
                            }
                        }
                    }
                    // 开始插入数据
                    DB::beginTransaction();
                    try {
                        foreach ($data as $d) {
                            $order_create = ['type' => $s->type, 'shop_id' => $s->id, 'order_sn' => $d['order_sn'], 'trade_type' => $d['trade_type'], 'confirm_time' => $d['confirm_time'], 'last_updated_at' => $d['updated_at'], 'confirm_status' => $d['confirm_status'], 'order_status' => $d['order_status'], 'after_sales_status' => $d['after_sales_status'], 'pay_amount' => $d['pay_amount'], 'logistics_id' => $d['logistics_id'], 'tracking_number' => $d['tracking_number']];
                            if ($d['shipping_time'] != '') {
                                $order_create['shipping_time'] = $d['shipping_time'];
                            }
                            if ($d['receive_time'] != '') {
                                $order_create['receive_time'] = $d['receive_time'];
                            }
                            if (isset($d['remark_tag'])) {
                                $order_create['remark_tag'] = $d['remark_tag'];
                                $order_create['remark_tag_name'] = $d['remark_tag_name'];
                            }
                            $order = Order::create($order_create);
                            // 订单附表，拼多多表
                            $pdd_create = [
                                'order_id' => $order->id,
                                'created_time' => $d['created_time'],
                                'receiver_name' => $d['receiver_name'],
                                'receiver_phone' => $d['receiver_phone'],
                                'receiver_address' => $d['receiver_address'],
                                'address' => $d['address'],
                                'province' => $d['province'],
                                'city' => $d['city'],
                                'town' => $d['town'],
                                'goods_amount' => $d['goods_amount'],
                                'discount_amount' => $d['discount_amount'],
                                'postage' => $d['postage'],
                                'order_change_amount' => $d['order_change_amount'],
                                'pay_no' => $d['pay_no'],
                                'pay_type' => $d['pay_type'],

                                'refund_status' => $d['refund_status'],
                                'last_ship_time' => $d['last_ship_time'],
                                'remark' => $d['remark'],
                                'self_contained' => $d['self_contained'],
                                'risk_control_status' => $d['risk_control_status'],
                                'shipping_type' => $d['shipping_type'],
                                'yyps_date' => $d['yyps_date'],
                                'delivery_one_day' => $d['delivery_one_day'],
                                'duoduo_wholesale' => $d['duoduo_wholesale'],
                                'mkt_biz_type' => $d['mkt_biz_type'],
                                'free_sf' => $d['free_sf'],
                                'is_pre_sale' => $d['is_pre_sale'],
                                'invoice_status' => $d['invoice_status'],
                                'is_pre_sale' => $d['is_pre_sale'],
                                'buyer_memo' => $d['buyer_memo'],
                                'stock_out_handle_status' => $d['stock_out_handle_status'],
                                'is_stock_out' => $d['is_stock_out'],
                            ];
                            if ($d['pay_time'] != '') {
                                $pdd_create['pay_time'] = $d['pay_time'];
                            }
                            if ($d['yyps_time'] != '') {
                                $pdd_create['yyps_time'] = $d['yyps_time'];
                            }
                            if ($d['urge_shipping_time'] != '') {
                                $pdd_create['urge_shipping_time'] = $d['urge_shipping_time'];
                            }
                            OrderPddData::create($pdd_create);
                            // 商品附表
                            $goods_insert = [];
                            $date = date('Y-m-d H:i:s');
                            foreach ($d['item_list'] as $g) {
                                $good = GoodSpec::where('sku_id', $g['sku_id'])->where('del_flag', 0)->first();
                                if (!is_null($good)) {
                                    $goods_insert[] = [
                                        'order_id' => $order->id,
                                        'good_id' => $good->good_id,
                                        'good_spec_id' => $good->id,
                                        'goods_spec' => $g['sku_id'],
                                        'goods_name' => $g['goods_name'],
                                        'good_spec_name' => $g['goods_spec'],
                                        'goods_price' => $g['goods_price'],
                                        'goods_img' => $g['goods_img'],
                                        'goods_count' => $g['goods_count'],
                                        'gift_flag' => 0,
                                        'created_at' => $date,
                                        'updated_at' => $date,
                                    ];
                                }
                            }
                            foreach ($d['gift_list'] as $gift) {
                                $good = GoodSpec::where('sku_id', $g['sku_id'])->where('del_flag', 0)->first();
                                if (!is_null($good)) {
                                    $goods_insert[] = [
                                        'order_id' => $order->id,
                                        'good_id' => $good->good_id,
                                        'good_spec_id' => $good->id,
                                        'goods_spec' => $gift['sku_id'],
                                        'goods_name' => $gift['goods_name'],
                                        'good_spec_name' => $gift['goods_spec'],
                                        'goods_price' => $gift['goods_price'],
                                        'goods_img' => $gift['goods_img'],
                                        'goods_count' => $gift['goods_count'],
                                        'gift_flag' => 0,
                                        'created_at' => $date,
                                        'updated_at' => $date,
                                    ];
                                }
                            }
                            OrderGood::insert($goods_insert);
                        }
                        DB::commit();
                    } catch (\Throwable $th) {
                        DB::rollback();
                    }
                }
            }
        }
        return $this->resData(200, '拉取成功...');
    }
}
